<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2018/12/28
 * Time: 下午8:02
 */

namespace App\Lib;


use Illuminate\Support\Facades\Log;


class youme
{
    //private $talk_send_msg_url = "https://api.youme.im/v1/im/send_talk_channel_message";
    //private $app_key = "YOUMEE5AC87911448790A24EB3CC421E9052964BC3A2D";
    //private $app_secret = "nJlnoj3lWUJIgPbd0L7qszHiujBUMSaLGEhgTNsYsaHuu3HbwWVMcvREgyFRwrjxTQ2+YqTZdnCYmCOUf8EpH2iSY1KLvEvrc5Z/3vqvn3Dwz8ICDfKuqLa4/rpcDtb/6F6Kgs1VKsloXOIdrmiI1oTyPRb4+bb/8ScPTKBqj7sBAAE=";
    private $identifier = "admin";
    //private $api_key = "c666c9b9b033738e7fc8db8c95fe61bc";


    /**
     * 发送房间内消息
     * @param $room_id
     * @param $data
     * @return bool
     */
    public function send_room_msg($room_id, $data, $to_user_id = 'admin', $level = 0){

        $config = config('youme');

        $appkey = $config['appkey'];//$this->app_key;
        $identifier = $this->identifier;
        $curtime = time();
        $checksum = sha1($config['appsecret'] . $curtime);
        $url = sprintf($config['apihost'] . '/v1/im/send_talk_channel_message?appkey=%s&identifier=%s&curtime=%d&checksum=%s', $appkey, $identifier, $curtime, $checksum);
        $data = [
            'UserID'=>"admin",
            'ToChannelID'=>strval($room_id),
            'Msg'=>json_encode($data),
            'MsgID'=>rand(10000, 99999)
        ];
        write_log('youme_msg', 'send_msg', $data);
        $ret_data = curl_request($url, $data, 'json', 'POST');
        write_log('youme_msg', 'send_msg_recv', $ret_data);
        $ret_data = json_decode($ret_data, true);
        /*if ($ret_data['ErrorCode'] == 70093 && $level < 3){
            $level = $level + 1;
            sleep(0.3);
            $this->send_room_msg($room_id, $data, $to_user_id, $level);
        }*/
        if (!isset($ret_data['ErrorCode'])){
            return false;
        }
        if ($ret_data['ErrorCode'] == 0){
            return true;
        }
    }


    public function get_token($user_id){
        $config = config('youme');
        //Log::debug($config['appkey'] . $config['apikey'] . $user_id);
        return sha1($config['appkey'] . $config['apikey'] . $user_id);
    }
}